<template>
  <div class='detail-container page-container'>
    <el-form v-show="showView" :model='conditionForm' :rules='rules' ref='conditionForm' label-width='110px'>
      <div class='create-edit-post'>
        <el-row>
          <el-col :span='16'>
            <el-form-item prop='name' label='条件名称'>
              <el-input v-model='conditionForm.name' class='normal-input' :disabled='!isCreate'></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span='12'>
            <el-form-item label='条件关系'>
              <el-switch v-model='conditionForm.value' active-text='同时满足' inactive-text='任意满足'></el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span='7'>
            <el-form-item prop='orderItemOption' label='条件选项内容'>
              <el-select
                v-model='conditionForm.orderItemOption'
                @change='selectOptions'
                placeholder='请选择'
                filterable
                clearable
                class='normal-input'
              >
                <el-option
                  v-for='(item,index) in itemOptions'
                  :key='index'
                  :label='item.name'
                  :value='item.id'
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span='7'>
            <el-form-item prop='guizhe' label='条件关系'>
              <el-select
                @focus='secondSelect'
                v-model='conditionForm.guizhe'
                :placeholder='labelText'
                filterable
                clearable
                class='normal-input'
              >
                <el-option
                  v-for='(item,index) in condition'
                  :key='index'
                  :label='item.centreClassifyName'
                  :value='item.centreClassifyId'
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span='7'>
            <el-form-item prop='cont' label='条件值'>
              <div v-if="message==='acd'">
                <el-select
                  v-model='conditionForm.cont'
                  @focus='thirdSelect'
                  :placeholder='labelText'
                  filterable
                  clearable
                  class='normal-input'
                >
                  <el-option
                    v-for='(item,index) in condition2'
                    :key='index'
                    :label='item.value'
                    :value='item.value'
                  ></el-option>
                </el-select>
              </div>
              <div v-else-if="message==='ace'">
                <el-date-picker
                  type='date'
                  placeholder='选择订单日期'
                  v-model='conditionForm.cont'
                  format='yyyy 年 MM 月 dd 日'
                  value-format='yyyy-MM-dd'
                  class='normal-input'
                ></el-date-picker>
              </div>
              <div v-else>
                <el-input v-model='conditionForm.cont' placeholder='请输入条件值' class='normal-input'></el-input>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span='6'>
            <el-form-item label>
              <el-button
                type='primary'
                icon='el-icon-plus'
                size='mini'
                @click="handleAddClick('conditionForm')"
                circle
              ></el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <ul class='ul' v-for='(info, index) in myInfo' :key='index'>
          <el-row>
            <el-col :span='6'>
              <el-form-item prop='orderItemOption' label='条件名称'>
                <el-select
                  v-model='info.orderItemOption'
                  disabled
                  readonly
                  placeholder='请选择'
                  filterable
                  clearable
                  class='normal-input'
                >
                  <el-option
                    v-for='(item,index) in itemOptions'
                    :key='index'
                    :label='item.name'
                    :value='item.id'
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span='6'>
              <el-form-item prop='guizhe' label='条件关系'>
                <el-select
                  v-model='info.guizhe'
                  disabled
                  readonly
                  placeholder='条件关系'
                  @focus='secondSelect'
                  filterable
                  clearable
                  class='normal-input'
                >
                  <el-option
                    v-for='(item,index) in condition'
                    :key='index'
                    :label='item.centreClassifyName'
                    :value='item.centreClassifyId'
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span='6'>
              <el-form-item label='条件值'>
                <el-input
                  v-model='info.cont'
                  disabled
                  readonly
                  placeholder='判断值'
                  class='normal-input'
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span='4'>
              <el-form-item label>
                <el-button
                  type='primary'
                  icon='el-icon-minus'
                  size='mini'
                  @click='handleDelClick(index)'
                  circle
                ></el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </ul>
        <el-row>
          <el-col :span='24' class='submit-btn'>
            <el-button class='create-goods' type='primary' @click='submitForm()' v-text='label'></el-button>
          </el-col>
        </el-row>
      </div>
    </el-form>

    <div v-show="!showView">
      <el-table
              :data="tableData"
              border
              style="width: 100%;margin: 30px 20px;"
              v-loading="loading"
              :row-class-name="tableRowClassName">
        <el-table-column
                prop="conditionParamName"
                label="关系条件名称">
        </el-table-column>
        <el-table-column
                prop="conditionParamNumName"
                label="关注条件值">
        </el-table-column>
        <el-table-column
                prop="conditionParamTypeName"
                label="关注条件关系">
        </el-table-column>
      </el-table>
      <div style="text-align: center;">
        <el-button @click="go" type="primary">返回上一级</el-button>
      </div>
    </div>
  </div>
</template>
<script>
import 'vue-awesome/icons/plus';
import {
  getCondInfo,
  createCondition,
  getFirstSelectList,
  getSecondSelectList,
  getThirdSelectList
} from '@/api/condition';
import { getOrderInfo3001 } from '@/api/order';

export default {
  data() {
    return {
      showView:false,
      tableData:[],
      loading: true,
      isCreate: false,
      label: '返回',
      condId: '',
      value: true,
      conditionForm: {
        name: '',
        orderItemOption: '',
        guizhe: '',
        cont: ''
      },
      info: '',
      myInfo: [],
      labelText: '请先选择条件名称',
      conditionList: [],
      condition: [],
      condition2: [],
      itemOptions: [],
      message: '',
      rules: {
        name: [
          { required: true, message: '请输入正确的名称', trigger: 'blur' }
        ],
        orderItemOption: [
          { required: true, message: '请选择正确的条件内容', trigger: 'change' }
        ],
        guizhe: [
          { required: true, message: '请选择正确的条件关系', trigger: 'change' }
        ],
        cont: [
          { required: true, message: '请输入正确的条件值', trigger: 'blur' }
        ]
      }
    };
  },
  watch: {
    $route(to, from) {
      var id = from.path.trim();
      var u = '/keySetting/index';
      if (id.trim() == u.trim()) {
        this.condId = localStorage.getItem('condId');
        if (this.condId == 'undefined' || this.condId == null) {
          // 以新增模式打开
          this.isCreate = true;
          this.label = '提交';
          this.clearAll();
        } else {
          this.isCreate = false;
          this.label = '返回';
          this.getConditionInfo(this.condId);
        }
        this.initCondition();
      };
      if(this.$route.query.readOnly && this.$route.query.readOnly=='yes'){
          let that = this;


          getCondInfo(this.$route.query.id).then(res=>{

              if(res.code ==0){
                  that.tableData = res.data.conditionParamList;
              }
          }).catch(err=>{
              console.log(err)
          })

          this.showView = false;

      }else{
          this.showView=true;
      }

    }
  },
  created() {
      if(this.$route.query.readOnly && this.$route.query.readOnly=='yes'){
          let that = this;


          getCondInfo(this.$route.query.id).then(res=>{

              if(res.code ==0){
                  that.tableData = res.data.conditionParamList;
              }
          }).catch(err=>{
              console.log(err)
          })

          this.showView = false;

      }else{
          this.showView=true;
      }
    this.condId = localStorage.getItem('condId');
    if (this.condId == 'undefined' || this.condId == null) {
      // 以新增模式打开
      this.isCreate = true;
      this.label = '提交';
      this.clearAll();
    } else {
      this.isCreate = false;
      this.label = '返回';
      this.getConditionInfo(this.condId);
    }
    this.initCondition();
  },
  methods: {
    go(){
      this.$router.go(-1);
    },
    tableRowClassName({row, rowIndex}) {
          if (rowIndex === 1) {
              return 'warning-row';
          } else if (rowIndex === 3) {
              return 'success-row';
          }
          return '';
      },
    secondSelect() {
      let that = this;
      /* console.log(this.itemptions)
                console.log(this.conditionForm.orderItemOption)O*/
      var obj = {};

      this.itemOptions.forEach(function(ele) {
        if (ele.id == that.conditionForm.orderItemOption) {
          obj = ele;
        }
      });

      if (!obj.hasOwnProperty('id')) {
        return;
      }
      if (that.conditionForm.orderItemOption.indexOf('Time') > -1) {
        that.message = 'ace';
      } else if (
        that.conditionForm.orderItemOption.indexOf('totalPrice') > -1
      ) {
        that.message = '';
      } else {
        that.message = 'acd';
      }

      getSecondSelectList(obj.id, obj.classifyType)
        .then(res => {
          that.condition = res.data;
        })
        .catch(err => {
          console.log(err);
        });
    },
    thirdSelect() {
      let that = this;
      let obj = {};
      this.itemOptions.forEach(function(ele) {
        if (ele.id == that.conditionForm.orderItemOption) {
          obj = ele;
        }
      });

      getThirdSelectList(obj.id, obj.classifyType)
        .then(res => {
          that.condition2 = res.data;
          console.log(res.data);
        })
        .catch(err => {
          console.log(err);
        });
    },
    selectOptions() {
      var str = this.conditionForm.orderItemOption;
      for (let i of this.conditionList) {
        if (i.conditionParam == str) {
          this.condition = [];
          //选择内容，二级联动
          var map = i.paramTypes;
          for (let j of map) {
            var m = {
              id: j.paramType,
              name: j.paramValue
            };
            this.condition.push(m);
            var paramvalue = i.paramValueTypeSearchValue;
            this.condition2 = [];
            if (
              paramvalue == '3001' ||
              paramvalue == '3003' ||
              paramvalue == '3004' ||
              paramvalue == '3005' ||
              paramvalue == '3007' ||
              paramvalue == '3008' ||
              paramvalue == '3009' ||
              paramvalue == '3010' ||
              paramvalue == '3011' ||
              paramvalue == '3012' ||
              paramvalue == '3013'
            ) {
              this.message = 'acd';
              getOrderInfo3001(paramvalue) //国别地区//已修改
                .then(data => {
                  var myData = data.data;
                  // console.log('国别数据11:',myData);
                  if (myData.length > 0) {
                    // console.log('国别数据12:',myData.length);
                    //加入数据内容
                    for (let i of myData) {
                      var map = {
                        key: i.configKey,
                        value: i.configValue
                      };
                      this.condition2.push(map);
                    }
                    this.conditionForm.cont = '';
                  }
                })
                .catch(function(error) {
                  console.log(error);
                });
            } else if ('orderTime' == str || 'deliveryTime' == str) {
              this.message = 'ace';
            } else {
              this.message = '';
            }
          }
          this.conditionForm.guizhe = '';
          this.conditionForm.cont = '';
        }
      }
      this.labelText = '请选择条件值';
    },
    handleAddClick(formName) {
      let that = this;
      this.$refs[formName].validate(valid => {
        if (valid) {
          let firstName = '';
          let secondName = '';
          let thirdName = '';
          this.itemOptions.forEach(function(ele) {
            if (ele.id == that.conditionForm.orderItemOption) {
              firstName = ele.name;
              console.log(firstName);
            }
          });
          this.condition.forEach(function(ele2) {
            if (ele2.centreClassifyId == that.conditionForm.guizhe) {
              secondName = ele2.centreClassifyName;
              console.log(secondName);
            }
          });
          if (that.message == 'acd') {
            this.condition2.forEach(function(ele3) {
              if (ele3.value == that.conditionForm.cont) {
                thirdName = ele3.value;
              }
            });
          } else {
            thirdName = that.conditionForm.cont;
          }
          var str = {
            orderItemOption: this.conditionForm.orderItemOption,
            guizhe: this.conditionForm.guizhe,
            cont: thirdName,
            conditionParamName: firstName,
            conditionParamTypeName: secondName,
            conditionParamNumName: this.conditionForm.cont
          };
          this.myInfo.push(str);
          //清空数据
          var name = this.conditionForm.name;
          this.conditionForm.orderItemOption = '';
          this.conditionForm.guizhe = '';
          this.conditionForm.cont = '';
          this.$refs['conditionForm'].resetFields();
          this.conditionForm.name = name;
        }
      });
    },
    handleDelClick(index) {
      this.myInfo.splice(index, 1);
    },
    initCondition() {
      let that = this;
      that.conditionList = [];
      that.itemOptions = [];
      that.condition = [];
      getFirstSelectList()
        .then(data => {
          that.conditionList = data.data;
          console.log('====');
          console.log(that.conditionList);
          for (let i of that.conditionList) {
            var map = {
              id: i.bigClassifyId,
              name: i.bigClassifyName,
              classifyType: i.classifyType
            };
            that.itemOptions.push(map);
          }
          that.labelText = '请先选择条件名称';
          that.loading=false;
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    submitForm() {
      let that = this;

      var bFlag = true;
      if (that.isCreate == false) {
        that.$router.push({
          path: '/keySetting/index',
          query: { id: Math.random() }
        });
      } else {
        if (that.myInfo.length <= 0) {
          this.$refs['conditionForm'].validate(valid => {
            if (valid) {
              let firstName = '';
              let secondName = '';
              let thirdName = '';
              this.itemOptions.forEach(function(ele) {
                if (ele.id == that.conditionForm.orderItemOption) {
                  firstName = ele.name;
                  console.log(firstName);
                }
              });
              this.condition.forEach(function(ele2) {
                if (ele2.centreClassifyId == that.conditionForm.guizhe) {
                  secondName = ele2.centreClassifyName;
                  console.log(secondName);
                }
              });
              if (that.message == 'acd') {
                this.condition2.forEach(function(ele3) {
                  if (ele3.value == that.conditionForm.cont) {
                    thirdName = ele3.key;
                  }
                });
              } else {
                thirdName = that.conditionForm.cont;
              }
              var str = {
                orderItemOption: this.conditionForm.orderItemOption,
                guizhe: this.conditionForm.guizhe,
                cont: thirdName,
                conditionParamName: firstName,
                conditionParamTypeName: secondName,
                conditionParamNumName: this.conditionForm.cont
              };
              this.myInfo.push(str);
            } else {
              that.$message.error('数据输入错误，请核对！');
              bFlag = false;
            }
          });
        }
        if (bFlag == true) {
          var conditionType = that.value == true ? '0' : '1';
          var list = [];
          for (let i of that.myInfo) {
            var map = {
              conditionParam: i.orderItemOption,
              conditionParamType: i.guizhe,
              conditionParamNum: i.cont,
              conditionParamName: i.conditionParamName,
              conditionParamTypeName: i.conditionParamTypeName,
              conditionParamNumName: i.conditionParamNumName
            };
            list.push(map);
          }
          var conditionParams = JSON.stringify(list);
          createCondition(
            that.conditionForm.name,
            conditionType,
            conditionParams
          )
            .then(data => {
              that.loading = false;
              console.log('条件提交成功', data);
              that.$router.push({
                path: '/keySetting/index',
                query: { id: Math.random() }
              });
            })
            .catch(function(error) {
              console.log(error);
            });
        }
      }
    },
    getConditionInfo(id) {
      let that = this;
      that.loading = true;
      that.conditionForm.name = '';
      that.conditionForm.orderItemOption = '';
      that.conditionForm.guizhe = '';
      that.conditionForm.cont = '';
      that.myInfo.splice(0, this.myInfo.length);
      //获取条件
      getCondInfo(id)
        .then(data => {
          var myData = data.data;
          that.conditionForm.name = myData.conditionInfo.conditionName;
          that.value = myData.conditionInfo.conditionType == '0' ? true : false;
          var conditionParamList = myData.conditionParamList;
          for (let i of conditionParamList) {
            var map = {
              orderItemOption: i.conditionParam,
              guizhe: i.conditionType,
              cont: i.conditionNum
            };
            that.myInfo.push(map);
          }
          that.loading = false;
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    clearAll() {
      this.conditionForm.name = '';
      this.conditionForm.orderItemOption = '';
      this.conditionForm.guizhe = '';
      this.conditionForm.cont = '';
      this.myInfo.splice(0, this.myInfo.length);
    }
  },
};
</script>
<style rel='stylesheet/scss' lang='scss' scoped>
@import 'src/styles/mixin.scss';
.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}
.page-container {
  width: 1000px;
}

.create-edit-post {
  padding: 20px;
}

.item-label {
  float: left;
  box-sizing: border-box;
  font-size: 14px;
  width: 70px;
  line-height: 80px;
}

.form-upload-img {
  margin-bottom: 20px;
}

.ul {
  padding-inline-start: 0px;
}

.logo-item {
  float: left;
}
.editor-container {
  margin-bottom: 20px;
}

.normal-input {
  width: 100%;
}

.create-goods {
  margin-bottom: 10px;
}

.submit-btn {
  text-align: center;
  margin-top: 20px;
  .el-button {
    width: 200px;
  }
}
</style>
